﻿using System;
using System.Collections.Generic;
using JWT;
using JWT.Serializers;
using JWT.Algorithms;
using Nancy.Json;

namespace StudyStationWEBAPI.Models
{
    public class TokenInfo
    {
        public TokenInfo(string user_name)
        {
            this.user_name = user_name;
        }
        public TokenInfo() { }
        public string user_name { get; set; }

    }

    public class TokenHelper
    {
        public static string SecretKey = "8XfWheKnHcpobI8i37uRihQsU6bqujIn";//这个服务端加密秘钥 属于私钥
        private static JavaScriptSerializer myJson = new JavaScriptSerializer();
        public static string GenToken(TokenInfo M)
        {
            var payload = new Dictionary<string, dynamic>
            {
                // {"UserName", M.UserName},//用于存放当前登录人账户信息
                {"user_name",M.user_name }
            };
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
            return encoder.Encode(payload, SecretKey);
        }

        public static TokenInfo DecodeToken(string token)
        {
            try
            {
                var json = GetTokenJson(token);
                TokenInfo info = myJson.Deserialize<TokenInfo>(json);
                return info;
            }
            catch (Exception)
            {

                throw;
            }
        }

        public static string GetTokenJson(string token)
        {
            try
            {
                IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                IJsonSerializer serializer = new JsonNetSerializer();
                IDateTimeProvider provider = new UtcDateTimeProvider();
                IJwtValidator validator = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
                var json = decoder.Decode(token, SecretKey, verify: true);
                return json; // 返回json形式的token
            }
            catch (Exception)
            {
                throw;
            }
        }
    }

}
